﻿using DevExpress.XtraReports.Web.WebDocumentViewer;
using Microsoft.AspNetCore.Mvc;
using ReportDesignerServer.Models;

namespace ReportDesignerServer.Controllers
{
    /// <summary>
    /// PrintController
    /// </summary>
    [ApiExplorerSettings(IgnoreApi = true)]
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class PrintController : ControllerBase
    {
        readonly IWebDocumentViewerReportResolver reportResolver;
        public PrintController(IWebDocumentViewerReportResolver reportResolver)
        {
            this.reportResolver = reportResolver;
        }

        /// <summary>
        /// 打印pdf
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<IActionResult> PrintPdf(string id)
        {
            var reportName = id.Split('|')[0];
            var pvid = id.Split('|')[1];
            var fileName = $"{reportName}-{pvid}.pdf";
            try
            {
                var report = reportResolver.Resolve($"{reportName}|{pvid}");
                await report.ExportToPdfAsync(fileName);//生成pdf文件
                if (System.IO.File.Exists(fileName))
                {
                    var memory = new MemoryStream();
                    using (var strem = new FileStream(fileName, FileMode.Open))
                    {
                        await strem.CopyToAsync(memory);
                    }
                    memory.Position = 0;
                    return File(memory, "application/pdf", fileName);
                }
                else
                {
                    return NotFound($"{fileName}文件不存在");
                }
            }
            catch (Exception ex)
            {
                return NotFound(ex.Message);
            }
            finally
            {
                if (System.IO.File.Exists(fileName))
                {
                    System.IO.File.Delete(fileName);
                }
            }
        }

    }
}
